package org.migrantalks.utils;

import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.core.shareddata.LocalMap;
import io.vertx.core.shareddata.SharedData;
import io.vertx.ext.jdbc.JDBCClient;
import org.apache.commons.io.IOUtils;

import java.io.InputStream;

/**
 * 数据库连接
 */
public class JdbcUtils {

    private JDBCClient dbClient;
    private static JsonObject config;

    static {

        byte[] buff = new byte[102400];
        try {

            InputStream ins = JdbcUtils.class.getClassLoader().getResourceAsStream("conf/config.json");
            int i = IOUtils.read(ins, buff);
            config = new JsonObject(new String(buff, 0, i));

        } catch (Exception e) {

            System.out.println("读取配置文件失败");
        }
    }

    public JdbcUtils(Vertx vertx, String env) {

        JsonObject envConfig = config.getJsonObject(env);
        if (envConfig == null) {
            throw new RuntimeException("没有找到指定的数据源");
        }

        JsonObject dbConfig = envConfig.getJsonObject("dataSource");
        dbClient = JDBCClient.createShared(vertx, dbConfig);
    }

    public JdbcUtils(Vertx vertx, JsonObject dbConfig) {
        dbClient = JDBCClient.createShared(vertx, dbConfig);
    }

    public JdbcUtils(Vertx vertx) {
        this(vertx, "dev");
    }

    public JDBCClient getDbClient() {
        return dbClient;
    }
}
